<template>
  <div class="countdown-container">
    <h2 class="countdown-title">签到倒计时</h2>
    <div class="countdown-timer" v-if="!isEnded">
      <div class="countdown-section">
        <span class="countdown-value">{{ minutes }}</span>
        <span class="countdown-label">分</span>
      </div>
      <div class="countdown-section">
        <span class="countdown-value">{{ seconds }}</span>
        <span class="countdown-label">秒</span>
      </div>
      <div class="countdown-section">
        <span class="countdown-value">{{ milliseconds }}</span>
        <span class="countdown-label">毫秒</span>
      </div>
    </div>
    <div v-else class="countdown-ended">
      <p>签到已结束</p>
    </div>
    <div v-if="!isEnded && !isSigned" class="sign-in-button-container">
      <el-button class="sign-in-button" @click="signIn">签到</el-button>
    </div>
    <div v-else-if="isSigned" class="sign-in-success">
      <p>签到成功</p>
    </div>
  </div>
</template>

<script>
import { signIn } from '@/utils/urlManager';
import axios from 'axios';
import '@/utils/InterceptorUtils'

export default {
  name: 'StudentCountdown',
  props: {
    timeEnd: Object
  },
  data() {
    return {
      intervalId: null,
      isEnded: false,
      isSigned: false, // 新增变量，用于判断是否已签到
      minutes: 0,
      seconds: 0,
      milliseconds: 0,
      deadline: null
    };
  },
  watch: {
    // 监听 timeEnd 的变化，重新启动倒计时
    timeEnd(newTimeEnd) {
      this.restartCountdown();
    }
  },
  methods: {
    updateCountdown() {
      const now = new Date().getTime();
      const timeLeft = this.deadline - now;

      if (timeLeft <= 0) {
        clearInterval(this.intervalId);
        this.isEnded = true;
        this.$message.success("签到已结束");
        return;
      }

      this.minutes = Math.floor(timeLeft / (60 * 1000));
      this.seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);
      this.milliseconds = Math.floor((timeLeft % 1000) / 10);
    },
    startCountdown(flag) {
      if (flag) {
        this.deadline = new Date(this.timeEnd.timeEnd).getTime();
      } else {
        this.deadline = localStorage.getItem("deadline")
      }
      localStorage.setItem("deadline", this.deadline)
      this.intervalId = setInterval(this.updateCountdown, 10);
      this.updateCountdown();
    },
    restartCountdown() {
      // 停止旧的倒计时
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
      // 重置倒计时状态
      this.isEnded = false;
      this.isSigned = false; // 重置签到状态
      this.minutes = 0;
      this.seconds = 0;
      this.milliseconds = 0;
      // 启动新的倒计时
      this.startCountdown(true);
    },
    signIn() {
      if (this.isEnded) {
        this.$alert('签到已结束', '提示', {
          confirmButtonText: '确定',
          type: 'info'
        });
      } else {
        clearInterval(this.intervalId); // 停止倒计时
        this.isSigned = true; // 设置已签到状态
        const params = {
            subjectId: this.timeEnd.subjectId
          }
        axios.put(signIn,null,{params})
          .then((response) => {
            if (response.data.data === 1) {
              this.$message.success('签到成功');
            }
            else {
              this.$message.warning("签到失败");
              this.isSigned = false; // 如果签到失败，恢复未签到状态
              this.restartCountdown(); // 重新启动倒计时
            }
          })
          .catch((err) => {
            console.error(err);
            this.$message.error("签到失败");
            this.isSigned = false; // 如果签到失败，恢复未签到状态
            this.restartCountdown(); // 重新启动倒计时
          });
      }
    }
  },
  mounted() {
    this.startCountdown(true);
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }
};
</script>

<style scoped>
.countdown-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f0f0f0;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  margin: 0 auto;
}

.countdown-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.countdown-timer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.countdown-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 10px;
}

.countdown-value {
  font-size: 70px;
  font-weight: bold;
  color: #4caf50;
  margin-bottom: 5px;
  transition: color 0.3s ease;
}

.countdown-label {
  font-size: 24px;
  color: #666;
}

.countdown-ended {
  font-size: 24px;
  color: #f44336;
  margin-top: 20px;
}

.sign-in-button-container {
  margin-top: 20px;
}

.sign-in-button {
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

.sign-in-button:hover {
  background-color: #45a049;
}

.sign-in-success {
  font-size: 24px;
  color: #4caf50;
  margin-top: 20px;
}
</style>